<template>
  <el-dialog
    v-model="drawerVisible"
    :destroy-on-close="true"
    :title="`${drawerProps.title}客户`"
    width="74%"
    top="10vh"
    draggable
    custom-class="user-info-dialog"
  >
    <div class="info-container">
      <el-scrollbar height="100%">
        <el-form
          ref="ruleFormRef"
          label-width="100px"
          label-suffix=" :"
          :rules="rules"
          :disabled="drawerProps.isView"
          :model="drawerProps.row"
          :hide-required-asterisk="drawerProps.isView"
          label-position="top"
        >
          <div class="form-item-title">基本信息</div>
          <div class="info-form">
            <el-form-item label="客户公司名称" prop="name">
              <el-input v-model="drawerProps.row!.name" placeholder="请填写客户公司名称" clearable></el-input>
            </el-form-item>
            <el-form-item label="上级客户" prop="parentId">
              <el-select v-model="drawerProps.row!.parentId" placeholder="请选择上级客户" clearable>
                <el-option v-for="item in companyList" :key="item.name" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="客户类型" prop="typeId">
              <el-select v-model="drawerProps.row!.typeId" placeholder="请选择客户类型" clearable>
                <el-option
                  v-for="item in drawerProps.dictList[dict.customerType]"
                  :key="item.name"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="客户来源" prop="sourceId">
              <el-select v-model="drawerProps.row!.sourceId" placeholder="请选择客户来源" clearable>
                <el-option
                  v-for="item in drawerProps.dictList[dict.customerSource]"
                  :key="item.name"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="客户星级" prop="code">
              <el-rate v-model="drawerProps.row!.importanceId" :colors="['#5378F6', '#5378F6', '#5378F6']" />
            </el-form-item>
            <el-form-item label="意向车型" prop="companyProductsed">
              <el-select v-model="drawerProps.row!.companyProductsed" :multiple="true" placeholder="请选择客户意向车型" clearable>
                <el-option v-for="item in drawerProps.productModelList" :key="item.name" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="所属行业" prop="industryId">
              <el-select v-model="drawerProps.row!.industryId" placeholder="请选择行业" clearable>
                <el-option
                  v-for="item in drawerProps.dictList[dict.industry]"
                  :key="item.name"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="项目阶段" prop="stageId">
              <el-select v-model="drawerProps.row!.stageId" placeholder="请选择项目阶段" clearable>
                <el-option
                  v-for="item in drawerProps.dictList[dict.customerStage]"
                  :key="item.name"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="客户状态" prop="status">
              <el-select v-model="drawerProps.row!.status" placeholder="请选择客户状态" clearable>
                <el-option
                  v-for="item in drawerProps.dictList[dict.customerStatus]"
                  :key="item.name"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="跟进人员" prop="userId">
              <el-select v-model="drawerProps.row!.userId" placeholder="请选择跟进人员" clearable filterable @change="changeUser">
                <el-option v-for="item in listAllUser" :key="item.name" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="协同人员" prop="jointUserId">
              <el-select
                v-model="drawerProps.row!.jointUserId"
                placeholder="请选择协同人员"
                clearable
                filterable
                @change="changeJointUser"
              >
                <el-option v-for="item in listAllUser" :key="item.name" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </div>
          <div class="form-item-title">客户联系人</div>
          <div class="info-form">
            <el-form-item label="首联系人" prop="contactPerson">
              <el-input v-model="drawerProps.row!.contactPerson" placeholder="请填写联系人" clearable></el-input>
            </el-form-item>
            <el-form-item label="联系人职务" prop="contactPosition">
              <el-input v-model="drawerProps.row!.contactPosition" placeholder="请填写联系人职务" clearable></el-input>
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="drawerProps.row!.contactNumber" placeholder="请填写联系电话" clearable></el-input>
            </el-form-item>
          </div>

          <!-- 用户列表 -->
          <div class="info-form" v-for="(item, key) in drawerProps.row.companyContacts" :key="key">
            <el-form-item label="联系人" prop="contactPerson">
              <el-input v-model="item!.contactPerson" placeholder="请填写联系人" clearable></el-input>
            </el-form-item>
            <el-form-item label="联系人职务" prop="contactPosition">
              <el-input v-model="item!.contactPosition" placeholder="请填写联系人职务" clearable></el-input>
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="item!.contactNumber" placeholder="请填写联系电话" clearable></el-input>
            </el-form-item>
            <el-form-item style="margin-top: 34px">
              <el-button type="danger" link @click="deleteContract(item, key)"> 删除 </el-button>
            </el-form-item>
          </div>
          <div>
            <el-button type="primary" style="margin-bottom: 20px" @click="addContacts">添加联系人</el-button>
          </div>

          <div class="form-item-title">预成交信息</div>
          <div class="info-form">
            <el-form-item label="预成交时间" prop="intentTime">
              <el-date-picker
                v-model="drawerProps.row!.intentTime"
                type="date"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择预成交时间"
              />
            </el-form-item>
            <el-form-item label="预成交金额" prop="intentAmount">
              <el-input-number
                controls-position="right"
                v-model="drawerProps.row!.intentAmount"
                placeholder="请填写预成交金额"
                clearable
              ></el-input-number>
            </el-form-item>
            <el-form-item label="预成交概率" prop="intentPercentage">
              <el-input-number
                v-model="drawerProps.row!.intentPercentage"
                controls-position="right"
                placeholder="请填写预成交概率"
                clearable
              ></el-input-number>
            </el-form-item>
          </div>
          <div class="form-item-title">所在地区</div>
          <div class="info-form">
            <el-form-item label="国家" prop="countryId">
              <el-select
                v-model="drawerProps.row!.countryId"
                placeholder="请选择国家"
                clearable
                filterable
                @change="changeCountry"
              >
                <el-option v-for="item in countryList" :key="item.countryName" :label="item.countryName" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item
              label="省市区"
              prop="addressed"
              v-if="!drawerProps.row!.countryId || drawerProps.row!.countryName === '中国'"
            >
              <el-cascader
                v-model="drawerProps.row!.addressed"
                :options="areaList"
                clearable
                :props="defaultOptions"
                ref="cascaderRef"
              />
            </el-form-item>
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="drawerProps.row!.address" placeholder="请填写详细地址" clearable></el-input>
            </el-form-item>
          </div>
          <div class="form-item-title">其他信息</div>
          <div class="info-form">
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" v-model="drawerProps.row!.remark" placeholder="请填写备注" clearable autosize></el-input>
            </el-form-item>
            <el-form-item label="竞品描述" prop="description">
              <el-input
                type="textarea"
                v-model="drawerProps.row!.description"
                placeholder="请填写备注"
                clearable
                autosize
              ></el-input>
            </el-form-item>
          </div>
          <div class="all-h"></div>
        </el-form>
      </el-scrollbar>
    </div>
    <template #footer>
      <el-button @click="drawerVisible = false"> 取消 </el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit"> 确定 </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="UserDrawer">
import { ref, reactive, onMounted, getCurrentInstance } from "vue"; // getCurrentInstance
const cxt = getCurrentInstance();
const dict = cxt?.appContext.config.globalProperties.$dict;
// import { genderType } from "@/utils/serviceDict";
import { useUserStore } from "@/stores/modules/user";
import { ElMessage, FormInstance, CascaderInstance } from "element-plus";
import { User, Dict, Role, Area, Country } from "@/api/interface";
// import UploadImg from "@/components/Upload/Img.vue";
import { getProvince, getCity, getDistrict, getCountryList, getListAllUser } from "@/api/modules/sys"; //getDict
import { getCompanyList } from "@/api/modules/customer";

const areaList: Area[] = ref();
let countryList: Country[] = reactive([]);
let listAllUser: User.ResUserList[] = reactive([]);
const cascaderRef = ref<CascaderInstance>();
const userStore = useUserStore();
let companyList = ref([]);
// 省市区
const defaultOptions = {
  lazy: true,
  label: "name",
  value: "code",
  checkStrictly: true,
  lazyLoad: async (node: Node, resolve: (data: Area) => void) => {
    let data = [];
    if (node.level === 1) {
      data = await getCitys({ code: node.data.code });
    } else if (node.level === 2) {
      data = await getDistricts({ code: node.data.code });
    }
    data = data.map(item => {
      item.leaf = node.level >= 2;
      return item;
    });
    resolve(data);
  }
};
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {},
  userStatus: [],
  userRoleList: [],
  dictList: {}
});
const rules = reactive({
  name: [{ required: true, message: "请填写客户公司名称" }],
  industryId: [{ required: true, message: "请选择所属行业" }],
  status: [{ required: true, message: "请选择客户状态" }],
  stageId: [{ required: true, message: "请选择项目阶段" }],
  userId: [{ required: true, message: "请选择跟进人员" }],
  typeId: [{ required: true, message: "请选择客户类型" }],
  sourceId: [{ required: true, message: "请选择客户来源" }],
  contactPerson: [{ required: true, message: "请填写首联系人" }],
  contactPosition: [{ required: true, message: "请填写首联系人" }],
  contactNumber: [{ required: true, message: "请填写首联系人" }],
  countryId: [{ required: true, message: "请选择国家" }],
  addressed: [{ required: true, message: "请选择省市区" }],
  address: [{ required: true, message: "请填写详细地址" }]
});

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<User.ResUserList>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
  userStatus: Dict.ResDictList[];
  userRoleList: Role.ReqRoleParams[];
  dictList: Dict.ResDictList;
}

const drawerVisible = ref(false);
// 获取全部公司
const getCompanyListFn = async () => {
  const { data } = await getCompanyList();
  companyList.value = data || [];
  if (drawerProps.value.row!.id) {
    companyList.value = companyList.value.filter(item => item.id != drawerProps.value.row!.id);
  }
};
// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  // 如果是新增，带出当前用户
  if (drawerProps.value.title === "新增") {
    drawerProps.value.row.userId = userStore.userInfo.id;
  }
  drawerVisible.value = true;
  getCountryListFn();
  getListAllUserFn();
  getCompanyListFn();
};

// 添加联系人
const addContacts = () => {
  const people = {
    contactPosition: "",
    contactPerson: "",
    contactNumber: ""
  };
  drawerProps.value.row.companyContacts.push(people);
};

// 删除联系人
const deleteContract = (row: any, index: number) => {
  drawerProps.value.row.companyContacts.splice(index, 1);
};
// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      console.log(drawerProps.value.row!.addressed);
      // 处理意向车型
      if (drawerProps.value.row.companyProductsed && drawerProps.value.row.companyProductsed.length) {
        drawerProps.value.row.companyProducts = drawerProps.value.row.companyProductsed.map(item => {
          const name = drawerProps.value.productModelList.find(itm => itm.id === item);
          return {
            productCategoryId: item,
            productCategoryName: name.name,
            productCategoryPicture: name.picture
          };
        });
      }
      // 省市区传值处理
      if (drawerProps.value.row!.addressed && drawerProps.value.row!.addressed.length) {
        let arrAddress = cascaderRef.value.getCheckedNodes();
        let names = arrAddress[0]["pathLabels"];
        let value = drawerProps.value.row!.addressed;
        drawerProps.value.row.province = names[0];
        drawerProps.value.row.provinceCode = value[0];
        drawerProps.value.row.city = names[1];
        drawerProps.value.row.cityCode = value[1];
        drawerProps.value.row.district = names[2];
        drawerProps.value.row.districtCode = value[2];
      }
      delete drawerProps.value.row.addressed;
      delete drawerProps.value.row.companyProductsed;
      await drawerProps.value.api!(drawerProps.value.row);
      // 处理省市区的传值
      ElMessage.success({ message: `${drawerProps.value.title}客户成功！` });
      drawerProps.value.getTableList!();
      drawerVisible.value = false;
      // 如果当前编辑是自己
      // if (drawerProps.value.row.id && userStore.userInfo.id === drawerProps.value.row.id) {
      //   mittBus.emit("refreshUserInfo");
      // }
    } catch (error) {
      console.log(error);
    }
  });
};

defineExpose({
  acceptParams
});
const getCitys = async (params: Area) => {
  const { data } = await getCity(params);
  return data || [];
};
const getDistricts = async (params: Area) => {
  const { data } = await getDistrict(params);
  return data || [];
};
// 获取国家
const getCountryListFn = async () => {
  const { data } = await getCountryList();
  countryList = data || [];
};

// 获取全部用户
const getListAllUserFn = async () => {
  const { data } = await getListAllUser();
  listAllUser = data || [];
};
// 国家监听改变
const changeCountry = item => {
  const country = countryList.find(itm => itm.id === item);
  if (country?.countryName != "中国") {
    drawerProps.value.row.addressed = [];
  }
  drawerProps.value.row.countryName = country?.countryName;
};
// 协同人员
const changeJointUser = item => {
  const user = listAllUser.find(itm => itm.id === item);
  drawerProps.value.row.jointUserName = user?.name;
};
// 人员
const changeUser = item => {
  const user = listAllUser.find(itm => itm.id === item);
  drawerProps.value.row.userName = user?.name;
};

onMounted(async () => {
  // 获取省份
  const result = await getProvince();
  areaList.value = result.data;
  getCountryListFn();
  getListAllUserFn();
  // if (drawerProps.value.title != "新增") {
  //   rules.password = [];
  // } else {
  //   rules.password =
  // }
  // ruleFormRef.value && ruleFormRef.value.clearValidate();
});
</script>
<style lang="scss">
:deep(.user-info-dialog) {
  display: flex;
  height: 600px;
}
.info-container {
  height: 580px;
}
.info-form {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  grid-gap: 0 30px;
  .el-select,
  .el-cascader,
  .el-date-editor {
    width: 100%;
  }
}
.all-h {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  grid-gap: 0 30px;
  width: 100%;
}
.form-item-title {
  margin: 20px 0 30px;
  font-size: 16px;
  font-weight: 600;
}
.el-input,
.el-select,
.el-input-number,
.el-cascader {
  width: 100% !important;
}
</style>
